package com.lbj.metalmax.p001

import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.workDataOf

/**
 * 创建工作者，继承 Worker
 */
class MyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {

    /**
     * 执行后台任务，在子线程中执行
     */
    override fun doWork(): Result {
        // 获取传递进来的数据
        val data = inputData.getString(INPUT_KEY)

        Log.i("MyWorker", "start ==> $data")
        // 休眠5秒钟
        Thread.sleep(5000)

        val sp = applicationContext.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
        if ("A" == data) {
            var aValue = sp.getInt(data, 0)
            sp.edit().putInt(data, ++aValue).apply()
        } else if ("B" == data) {
            var bValue = sp.getInt(data, 0)
            sp.edit().putInt(data, --bValue).apply()
        }

        Log.i("MyWorker", "finish ==> $data")

        // 创建传递出去的数据
        val outputData = workDataOf(OUTPUT_KEY to "从 doWork() 方法往外传递给外层的数据")

        return Result.success(outputData)
    }
}